package org.example.collection.set;

import java.util.*;

public class Demo1 {
    public static void main(String[] args) {
//        test1();
        test2();
        test3();
    }

    private static void test3() {
        List<Student> students = List.of(new Student("ZhangSan", 28), new Student("lisi", 27),
                new Student("WangWu", 29), new Student("ZhaoLiu", 28), new Student("QianQi", 30));
        //创建集合对象
        TreeSet<Student> ts = new TreeSet<>(students);
        //遍历集合
        for (Student student : ts) {
            System.out.println("Student{ name='" + student.name + "', age=" + student.age + '}');
        }
    }

    private static <E> void test2() {
        //创建集合对象
        TreeSet<Teacher> ts = new TreeSet<>((o1, o2) -> {
            // o1表示现在要存入的那个元素, o2表示已经存入到集合中的元素
            // 主要条件
            int result = o1.age - o2.age;
            // 次要条件
            result = result == 0 ? o1.name.compareTo(o2.name) : result;
            return result;
        });
        ts.add(new Teacher("ZhangSan", 23));
        ts.add(new Teacher("lisi", 22));
        ts.add(new Teacher("WangWu", 24));
        ts.add(new Teacher("ZhaoLiu", 24));
        //遍历集合
        for (Teacher teacher : ts) {
            System.out.println("Teacher{ name='" + teacher.name + "', age=" + teacher.age + '}');
        }
    }

    public static class Student implements Comparable<Student> {
        public String name;
        public int age;

        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public int compareTo(Student o) {
            //按照对象的年龄进行排序
            //主要判断条件: 按照年龄从小到大排序
            int result = this.age - o.age;
            //次要判断条件: 年龄相同时，按照姓名的字母顺序排序
            result = result == 0 ? this.name.compareTo(o.name) : result;
            return result;
        }
    }

    public static class Teacher {
        public String name;
        public int age;

        public Teacher(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }

    private static void test1() {
        //创建集合对象
        Set<String> set = new TreeSet<>(Set.of("ccc", "aaa", "bbb"));
        set.add("aaa");
//        for (int i = 0; i < set.size(); i++) {
//            //Set集合是没有索引的，所以不能使用通过索引获取元素的方法
//        }
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {  // aaabbbccc
            System.out.print(it.next());
        }
        System.out.println();
        for (String s : set) {  // aaabbbccc
            System.out.print(s);
        }
        System.out.println();
        set.forEach(System.out::print); // aaabbbccc
    }
}
